<?php
/**
* feed_user token 模型
*
* @author hejigui <hejigui@soften.cn>
*/

class User_token_model extends CI_Model{

    const PLATFORM_SOHU = 'sohu';
    const PLATFORM_NETEASE = 'netease';
    const PLATFORM_TENCENT = 'tencent';
    const PLATFORM_SINA    = 'sina';
	const FEED_USER_TOKEN_TABLE = 'feed_user_token';
    private $_write_db;
	/**
	* __construct
	*
	* @access public
	* @return string $mixed
	*/
	public function __construct() {
		parent::__construct();
		$this->load->database();
        $this->load->library('error_code_library');
        $this->_write_db = $this->load->database('master', TRUE);
	}

	/**
	* 获取指定用户 当前(小时内)使用次数最少的token信息
	*
	* @access public
	* @param string $platform 用户所属开放平台 [Must]
	* @param string $uid 用户在开放平台uid [Must]
	* @return string $mixed
	*/
	public function get_token_byuid($platform,$uid) {
		if(empty($platform) || empty($uid)){
			log_message('error', " feedusertoken_model get_min_token param is error !! platform{$platform}--uid:{$uid}");
			return false;
		}

		$user_token_map['platform'] = $platform;
		$user_token_map['userid'] = $uid;

		return $this->get_min_token($user_token_map);
	}

	/**
	* 获取当前(小时内)使用次数最少的token信息
	* 若无可用token,情况如下:
	*         1 token有效超时--自动登录
	* 		  2 使用次数都超标--检查是否有新appkey,有则自动登录,一帐号在多个appkey下的自动登录.
	* @access public
	* @param array $map xxxxxx [Must]
	* @return string $mixed
	*/
	public function get_token_by_platform_bak($where) {
        $platform = $where['platform'];
        $where['status'] = 1;
        $where['lastlogin >'] = 0;

		if($platform == self::PLATFORM_NETEASE){
			$this->db->select('id,appkey,oauth_token,oauth_token_secret')->from(self::FEED_USER_TOKEN_TABLE)->where($where)->order_by("total", "asc")->limit(50);
		}

		if($platform == self::PLATFORM_TENCENT || $platform == self::PLATFORM_SOHU){
			$this->db->select('id,appkey,access_token,refresh_token,openid')->from(self::FEED_USER_TOKEN_TABLE)->where($where)->order_by("total", "asc")->limit(50);
		}

		if($platform == self::PLATFORM_SINA){
			$this->db->select('id,appkey,access_token,refresh_token')->from(self::FEED_USER_TOKEN_TABLE)->where($where)->order_by("total", "asc")->limit(50);
		}

		$query = $this->db->get();
        if($query->num_rows() > 0) {
            $result_array = $query->result_array();
            $rand_key = array_rand($result_array);
            return $result_array[$rand_key];
        } else {
            return $this->error_code_library->getError('system', 'data', 'no_data', 'In Function '. __FUNCTION__);
        }
	}




	/**
	* 获取当前(小时内)使用次数最少的token信息
	* 若无可用token,情况如下:
	*         1 token有效超时--自动登录
	* 		  2 使用次数都超标--检查是否有新appkey,有则自动登录,一帐号在多个appkey下的自动登录.
	* @access public
	* @param array $map xxxxxx [Must]
	* @return string $mixed
	*/
	public function get_token_by_platform($where) {
		return $this->get_rand_token($where);
	}



	/**
	* 获取当前(小时内)使用次数最少的5个token信息,然后随机返回一个
	* 1 使用次数超频的.将不会再使用...
	* 2 优先使用高等级的key
	*
	* 若无可用token,情况如下:
	*         1 token有效超时--自动登录
	* 		  2 使用次数都超标--检查是否有新appkey,有则自动登录,一帐号在多个appkey下的自动登录.
	* @access public
	* @param array $map xxxxxx [Must]
	* @return array $mixed
	*/
	public function get_rand_token($map) {
		if(empty($map['platform'])){
			log_message('error', "User_token_model get_rand_token param is error !! map:".var_export($map,true));
			return false;
		}

		$platform = $map['platform'];

		$map['status'] = 1;
		//$map['lastlogin >'] = 0;

		//已用次数小于本小时最大可用次数,使用次数超频的.将不会再使用...
		//$this->db->where('total < appkey_max_connect');

		if($platform == 'netease'){
			$this->db->select('id,appkey,oauth_token,oauth_token_secret');
		}

		if($platform == 'tencent'){
			$this->db->select('id,appkey,access_token,refresh_token,openid');
		}

		if($platform == 'sina' || $platform == 'sohu'){
			$this->db->select('id,appkey,access_token,refresh_token');
		}

		$order = 'appkey_max_connect` DESC , `total` ASC ';//优先使用高等级的key
		$query = $this->db->from(self::FEED_USER_TOKEN_TABLE)->where($map)->limit(50)->order_by($order)->get();
		//echo $this->db->last_query();

		if(false == ($token_list = $query->result_array())){
			log_message('debug', "User_token_model get_rand_token is empty !! sql is :".$this->db->last_query());
			return $this->error_code_library->getError('system', 'data', 'no_data', 'In Function '. __FUNCTION__);
		}else {
			$token_count = count($token_list);
			$rand_point = rand(0,$token_count-1);

			return $token_list[$rand_point];
		}
	}

	/**
	* 递增token的使用次数
	*
	* @access public
	* @param string $id token id [Must]
	* @return bool $mixed
	*/
	public function increase_total($id = NULL) {
        if(is_null($id)) {
            return $this->error_code_library->getError('system', 'params', 'no_must_parameter', 'ID In Function '. __FUNCTION__);
        } else {
            $this->_write_db->set('total', 'total+1', FALSE);
            $this->_write_db->where('`id` = '.$id);
            $result = $this->_write_db->update(self::FEED_USER_TOKEN_TABLE);
        }
		return true;
	}

	/**
	* 获取抓取开放平台数据 所需sleep时间
	*	todo 做一些优化检测,如：当一小时内剩余次数多时候可以适当将更新加快。
	*
	* @param string $platform 所要计算sleep时间的开放平台 [Must]
	* @param string $used_time 所要计算sleep时间已用的时间 [Must]
	* @access public
	* @return array $mixed
	*/
	public function get_need_sleep_time($platform,$used_time) {
		if(empty($platform) || empty($used_time)){
			return false;
		}

		$need_time = 0 ;
		switch($platform) {
			case 'sina':
				if($used_time>= 4) {
					$need_time = 0;
				}
				else{
					$need_time = 4 - $used_time;
				}
				break;
			case 'tencent':
				if($used_time>= 4) {
					$need_time = 0;
				}
				else{
					$need_time = 4 - $used_time;
				}
				break;
			case 'sohu':
				if($used_time>= 8) {
					$need_time = 0;
				}
				else{
					$need_time = 8 - $used_time;
				}
				break;
			case 'netease':
				if($used_time>= 19) {
					$need_time = 0;
				}
				else{
					$need_time = 19 - $used_time;
				}
				break;
		}

		return $need_time;
	}


	/**
	* 查询 token 是否存在
	*
	* @access public
	* @param string $platform 用户所属开放平台 [Must]
	* @param string $appkey  [Must]
	* @param string $userid 用户在开放平台uid [Must]
	* @return string $mixed
	*/
	public function is_exist($platform, $appkey, $userid) {

		if(empty($platform) || empty($appkey) || empty($userid))
		{
			log_message('error', " feedusertoken_model is_exist param is error !! platform{$platform}--appkey:{$appkey}--userid:{$userid}");
			return false;
		}
		$this->db->where('platform', $platform);
		$this->db->where('appkey', $appkey);
		$this->db->where('userid', $userid);

		$this->db->select('*')->from($this->feeduser_token_table);

		$query = $this->db->get();

		return $query->row_array();
	}

	/**
	* 修改用户token信息
	*
	* @access public
	* @param string $fid xxxxx
	* @param string $platform xxxxx [Must]
	* @param string $plat_uid xxxxx [Must]
	* @param string $nick xxxxx [Must]
	* @return string $mixed
	*/

	public function update_user_token($token_id, $tokeninfo = array(
			'platform'=>'',
		    'uid'=>'',
			'userid'=>'',
			'appkey'=>'',
			'access_token'=>'',
			'refresh_token'=>'',
			'oauth_token'=>'',
			'oauth_token_secret'=>'',
			'openid'=>'',
		)) {
		if(empty($token_id)){
			log_message('error', "Feedusertoken_model update_user_token param is error !! token_id:{$token_id}");
			return false;
		}
		$map = array_filter($tokeninfo);

        $this->_write_db->where('id', $token_id);

		//$this->db->where('userid', $userid);
		//$this->db->where('platform', $platform);

		return $this->_write_db->update($this->feeduser_token_table, $map);

	}

	/**
	* 增加用户token信息
	*
	* @access public
	* @param string $fid xxxxx
	* @param string $platform xxxxx [Must]
	* @param string $plat_uid xxxxx [Must]
	* @param string $nick xxxxx [Must]
	* @return string $mixed
	*/
	public function add_user_token($tokeninfo = array(
			'platform'=>'',
		    'uid'=>'',
			'userid'=>'',
			'appkey'=>'',
			'access_token'=>'',
			'refresh_token'=>'',
			'oauth_token'=>'',
			'oauth_token_secret'=>'',
			'openid'=>'',
		)){
		if(empty($tokeninfo['uid']) || empty($tokeninfo['userid']) || empty($tokeninfo['appkey']))
		{
			log_message('error', "Feedusertoken_model update_user_token param is error !! uid:{$uid}--userid:{$userid}--appkey:{$appkey}");
			return false;
		}
        $map = array_filter($tokeninfo);

        $map['addtime'] = time();
        $map['lastlogin'] = 1;
		$map['status'] = 1;

		return $this->_write_db->insert($this->feeduser_token_table, $map);

	}
	/**
	* 删除token 信息
	*
	* @access public
	* @param string $fid xxxxx
	* @param string $platform xxxxx [Must]
	* @param string $plat_uid xxxxx [Must]
	* @param string $nick xxxxx [Must]
	* @return string $mixed
	*/
	public function delete_user_token($token_id) {
		if(empty($token_id)){
			log_message('error', " Feeduserinfo_model delete_user_token param is error !! token_id:{$token_id}");
			return false;
		}
		$this->_write_db->where('id', $token_id);
		$rs = $this->_write_db->delete($this->feeduser_token_table);
		if(!$rs){
			log_message('error', " Feeduserinfo_model delete_user_token db->delete is fail !! id:{$token_id}");
			return false;
		}
		 return true;
	}
}

?>